package org.opu.pc;

import java.util.ArrayList;
import java.util.List;

import javax.swing.UIManager;
import org.opu.pc.security.SecurityActionFilter;
import org.opu.pc.security.UserDetailsData;
import org.opu.pc.services.SystemSettingsService;

import org.opu.pc.ui.client.MainView;
import org.opu.pc.ui.client.authentication.AuthenticationSystem;
import org.opu.pc.ui.util.NullableProperties;
import org.opu.pc.ui.util.Options;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.authentication.ProviderManager;

/**
 * @author Yuriy Dunko
 */
public class App {

    private static ApplicationContext context = null;
    private static SecurityActionFilter filter = new SecurityActionFilter();

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
        
    	try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
		}
    	
        try {
            NullableProperties prop = NullableProperties.getInstance();
            prop.load();
            
            context = new ClassPathXmlApplicationContext(
                    "classpath:ui_applicationcontext.xml",
                    "classpath:datasource_applicationcontext.xml",
                    "classpath:dao_applicationcontext.xml",
                    "classpath:sg_applicationcontext.xml",
                    "classpath:publications_analysis_applicationcontext.xml",
                    "classpath:services_applicationcontext.xml",
                    "classpath:desktop_ui_applicationcontext.xml",
                    "classpath:security_applicationcontext.xml");
        } catch (Exception ex) {
			Options.error("Fatal error have occured when loading context.\n"
                    + "Try to reconfigure application (in management)." + ex);
            ex.printStackTrace(System.out);
            System.exit(1);
        }

        AuthenticationSystem as = context.getBean("AuthenticationSystem", AuthenticationSystem.class);
        as.authenticat();
        startView();
    }

    public static void startView() throws BeansException {
        List actions = (List) context.getBean("Actions");
        MainView view = (MainView) context.getBean("MainView");
        view.getMainMenuBar().getI18n().addVar("user", UserDetailsData.getCurrentUser().getUsername());

        List availableActions = new ArrayList(actions);
        filter.cleanup(availableActions);

        view.initActions(availableActions);
        view.fireState();
        view.asFrame().setVisible(true);
    }
}
